// JavaScript Document
$(document).ready(function() {
  $('#edit-survey-search-active').datepicker({
    dateFormat:'mm-dd-yy'
  });
  $('#edit-survey-search-expire').datepicker({
    dateFormat:'mm-dd-yy'
  });
  
});

function applyAction(pageno, action){
  //prepare the field values for filtering
  var search_survey = $.trim($("#edit-survey-search-details").val());
  var search_active = $("#edit-survey-search-active").val();
  var search_expire = $.trim($("#edit-survey-search-expire").val());
  var search_status = $.trim($("#edit-survey-search-status").val());
  var sort = $('#hid_sort').val();
  $('#hid_pageno').val(pageno);
  //check for search criteria and return false if no value
  if (search_survey == "" && search_active == "" && search_expire == "" && search_status == "") {
    openAlertDialog(300, 125, 'Information', 'Please enter the search criteria');
    return;
  }
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();
  $.ajax({
    type : "POST",
    url : baseurl+"survey/actions/filter",
    data : "search_survey="+encodeURIComponent(search_survey)+"&search_active="+search_active+"&search_expire="+search_expire+"&search_status="+search_status+(pageno>1?'&page_no='+pageno:'')+(sort!=""?'&sorting='+sort:''),
    async : true,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno,10);
      var counter = $('#hid_totalRec').val();
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyAction('+(page-1)+',\'previous\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applyAction('+(page+1)+',\'next\')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
function closeDialog(testId){
  $('#dialog').dialog('destroy');
  makeArchived(testId);
}

function createSurvey(){
  openDialog("createsurvey",0,600,305,"Create Survey");
}

function editSurvey(id){
  
  reopen_dialog(600,305,$('#survey_title').html());
  //$('#dialog').html('<div style="padding-top:130px; padding-left:280px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'survey/edit/'+id,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('edit-survey-actdate',0);
      createDatePicker('edit-survey-expdate',0);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editQuestion(surveyid){
  reopen_dialog(850,500,"Add Question");
  editQuestionDialog(surveyid);
}
function previewQuestion(id){
  reopen_dialog(700,515,"Preview Question");
  preview_question_dialog(id);
}
function saveQuestions(surveyId, action, qid){
	var type = $('#edit-question-type').val();
  var question = ckeditor.getData();
  var refusestr = question.substring(question.length-7);
  if($.trim(refusestr)=="<br />"){
    question = question.substring(0,question.length-7);
  }
  var disp_order = $('#edit-question-displayorder').val();
  if(!disp_order || disp_order==0 || disp_order=="")
    disp_order = 1;
  var mand = $('#edit-question-mandatory').is(':checked');
	
  //code to validate the fields
  var lines = 10;
  var str = "";
  //if(type == "") {
	if(type=="" || type.toLowerCase()==("Choose Question Type".toLowerCase())){
    str += "Please select the question type";
    lines+=18;
  }
  if($.trim(question) == "" || $.trim(question) == "<br />") {
    if(str!="")
      str+= "<br/>";
    str += "Please add a question";
    lines+=18;
  }
  if(type != "" && type != "Textbox" && type != "Textarea" && answers.length==0) {
    if(str!="")
      str+= "<br/>";
    str += "Please add the answers for this question";
    lines+=18;
  }
  if (type != "Checkbox" && type != "Multiselect List" && type != "Multiselect Filtered List" && type != "Source-Target List") {
    var k=0;
    for(var i=0; i<answers.length; i++){
      if(answers[i][3] == 'true'){
        k++;
      }
    }
    if(k > 1){
      if(str!="")
        str+= "<br/>";
      str += "Please select only one default value";
      lines+=18;
    }
  }

  if (str != "") {
    resize_dialog(850,500+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
	
  if(type == "Radio button"){
    type = "Radiobutton";
  }
  else if(type=="Checkbox"){
    type = "Checkbox";
  }
  else if(type=="Dropdown List"){
    type = "Dropdown";
  }
  else if(type=="Multiselect List"){
    type = "Multiselect";
  }
  else if(type=="Textbox"){
    type = "Textbox";
  }
  else if(type=="Textarea"){
    type = "Textarea";
  }
  else if(type=="Filtered List"){
    type = "Filtered List";
  }
  else if(type=="Multiselect Filtered List"){
    type = "Multiselect Filtered List";
  }
	else if(type=="Source-Target List"){
    type = "Source-Target List";
  }
	
  get_answers();

  var ans_str = "";
  for(var i=0; i<answers.length; i++){
    if(ans_str!="")
      ans_str+="*#~*";
    ans_str += answers[i][0]+","+answers[i][1]+","+answers[i][2]+","+(answers[i][3]==''||answers[i][3]=='false'?'false':'true');
  }
  //Page loading animation
  $('#dialog').html('<div style="padding-top:175px; padding-left:350px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

	$.ajax({
		type : "POST",
		url : baseurl+"survey/edit_action/question"+((action=="edit"||action=="edit_add")?"/"+qid:""),
		data: "surveyid="+surveyId+"&qtype="+type+"&question="+encodeURIComponent(question)+"&answers="+encodeURIComponent(ans_str)+"&ismandatory="+mand+"&disp_order="+disp_order,
		async : true,
		cache : false,
		success : function (msg) {
			eval("var json="+msg);
			if(json.Message=="Success"){
				answers = new Array();
				if(action=="add"||action=="edit_add"){
					reopen_dialog(850,500,"Add Question");
					editQuestionDialog(surveyId);
				}else{
					reopen_dialog(700,515,"Preview Question");
					preview_question_dialog(surveyId);
				}
			}
		},
		error : function (res) {
			handleRequestError(res);
		}
	});
/*
	var type = $('#edit-question-type').val();
  var question = ckeditor.getData();
  var refusestr = question.substring(question.length-7);
  if($.trim(refusestr)=="<br />"){
    question = question.substring(0,question.length-7);
  }
  var disp_order = $('#edit-question-displayorder').val();
  if(!disp_order || disp_order==0 || disp_order=="")
    disp_order = 1;
  var mand = $('#edit-question-mandatory').is(':checked');
  if(type=="" || type.toLowerCase()==("Choose Question Type".toLowerCase())){
    $('#dialog').scrollTop(0);
    styleStatusMessages("Please select the question type", "statusMessage", "failure");
  }
  else if((question=="") || ($.trim(question)=="<br />")){
    $('#dialog').scrollTop(0);
    styleStatusMessages("Please enter question", "statusMessage", "failure");
  }else if (type != "Textbox" && type != "Textarea" && answers.length==0) {
    $('#dialog').scrollTop(0);
    styleStatusMessages("Please add the answers for this question", "statusMessage", "failure");
  }else{
    if(type == "Radio button"){
      type = "Radiobutton";
    }else if(type=="Checkbox"){
      type = "Checkbox";
    }else if(type=="Dropdown List"){
      type = "Dropdown";
    }else if(type=="Multiselect List"){
      type = "Multiselect List";
    }else if(type=="Textbox"){
      type = "Textbox";
    }else if(type=="Textarea"){
      type = "Textarea";
    }else if(type=="Filtered List"){
      type = "Filtered List";
    }else if(type=="Multiselect Filtered List"){
      type = "Multiselect Filtered List";
    }else if(type=="Source-Target List"){
      type = "Source-Target List";
    }
    // Get all the answers with proper order
    get_answers();
    
    if (type != "Checkbox" && type != "Multiselect List" && type != "Multiselect Filtered List" && type != "Source-Target List") {
      var k=0;
      for(var i=0;i<answers.length;i++){
        if(answers[i][3]=='true' || answers[i][3]==true){
          k++;
        }
      }
      if(k>1){
        styleStatusMessages("Please select only one default value", "statusMessage", "failure");
        $('#dialog').scrollTop(0);
        return false;
      }
    }

    $('#dialog').html('<div style="padding-top:175px; padding-left:350px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
    var ans_str = "";
    for(var i=0;i<answers.length;i++){
      if(ans_str!="")
        ans_str+="*#~*";
      ans_str += answers[i][0]+","+answers[i][1]+","+answers[i][2]+","+(answers[i][3]==''||answers[i][3]=='false'?'false':'true');
    }
    $.ajax({
      type : "POST",
      url : baseurl+"survey/edit_action/question"+((action=="edit"||action=="edit_add")?"/"+qid:""),
      data: "surveyid="+surveyId+"&qtype="+type+"&question="+encodeURIComponent(question)+"&answers="+encodeURIComponent(ans_str)+"&ismandatory="+mand+"&disp_order="+disp_order,
      async : true,
      cache : false,
      success : function (msg) {
        eval("var json="+msg);
        if(json.Message=="Success"){
          answers = new Array();
          if(action=="add"||action=="edit_add"){
            reopen_dialog(850,500,"Add Question");
            editQuestionDialog(surveyId);
          }else{
            reopen_dialog(700,515,"Preview Question");
            preview_question_dialog(surveyId);
          }
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }
  return false;*/
}

function submitSurvey(){
  var title = $.trim($('#edit-survey-title').val());
  var desc = $.trim($('#edit-survey-description').val());
  var lang = "EN";
  var actDate = $.trim($('#edit-survey-actdate').val());
  var expDate = $.trim($('#edit-survey-expdate').val());
  var status = $('#edit-survey-status').val();
  //var siteid = $('#edit-survey-site').val();

  var lines = 10;
  var str = "";
    
  if(title==""){
    str += "Title should not be empty";
    lines+=18;
  }else if(title.length>50){
    if(str!="")
      str+= "<br/>";
    str = "Title should not be more than 50 characters";
    lines+=18;
  }
  if(desc!="" && desc.length>1000){
    if(str!="")
      str+= "<br/>";
    str += "Description should not be more than 1000 characters";
    lines+=18;
  }
  if(actDate==""){
    if(str!="")
      str+= "<br/>";
    str += "Activation date should not be empty";
    lines+=18;
  }
  if(status==0){
    if(str!="")
      str+= "<br/>";
    str += "Select any status";
    lines+=18;
  }
  if (expDate != "") {
    var actObj = new Date(actDate.replace(/-/g,"/"))
    var expObj = new Date(expDate.replace(/-/g,"/"))
    if (actObj > expObj) {
      if(str!="")
        str+= "<br/>";
      str += "Expiration date should be greater than or equal to the Activation date";
      lines+=18;
    }
  }


  var actdate = actDate.split("-");
  if(actdate.length <3){
    if(str!="") str+= "<br/>";
    str += 'Please enter Valid date in Activation date field';
    lines+=18;
  }

  if(expDate!=''){
	  var expdate = expDate.split("-");
	  if(expdate.length <3){
		if(str!="") str+= "<br/>";
		str += 'Please enter Valid date in Expiration date field';
		lines+=18;
	  }
  }

  if(str!=""){
    resize_dialog(600, 305+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    return;
  }

  var pageno = $("#hid_pageno").val();
  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+"survey/create",
    data: "title="+encodeURIComponent(title)+"&desc="+encodeURIComponent(desc)+"&actDate="+actDate+"&expDate="+expDate+"&status="+status+"&lang="+lang,
    async : true,
    cache : false,
    success : function (msg) {
      eval("var json="+msg);
      if(json.Message=="Success"){
        applyAction(pageno,$('#edit-apply').attr('actionitem'));
        reopen_dialog(850,500,"Add Question");
        editQuestionDialog(json.evaluationId);
      }else{
        if(json.Error=="survey name already exist"){
          $.ajax({
            type : "GET",
            url : baseurl+'survey/edit/0',
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              createDatePicker('edit-survey-expdate',0);
              createDatePicker('edit-survey-actdate',0)

              $('#edit-survey-description').val(desc);
              $('#edit-survey-title').val(title);
              $('#edit-survey-description').val(desc);
              $('#edit-survey-actdate').val(actDate);
              $('#edit-survey-expdate').val(expDate);
              $('#edit-survey-status').val(status);
              styleStatusMessages("Survey name already exists", "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
          resize_dialog(600, 305+30);
        }else{
          $.ajax({
            type : "GET",
            url : baseurl+'survey/edit/0',
            async : true,
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              createDatePicker('edit-survey-expdate',0);
              createDatePicker('edit-survey-actdate',0)

              $('#edit-survey-description').val(desc);
              $('#edit-survey-title').val(title);
              $('#edit-survey-description').val(desc);
              $('#edit-survey-actdate').val(actDate);
              $('#edit-survey-expdate').val(expDate);
              $('#edit-survey-status').val(status);
              styleStatusMessages("Failure to save survey", "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
          resize_dialog(600, 305+30);
        }
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editSurveySave(id){
  var title = $.trim($('#edit-survey-title').val());
  var desc = $.trim($('#edit-survey-description').val());
  //var lang = $('#edit-survey-language').val();
  var lang = "EN";
  var actDate = $.trim($('#edit-survey-actdate').val());
  var expDate = $.trim($('#edit-survey-expdate').val());
  var status = $('#edit-survey-status').val();
  var siteid = $('#edit-survey-site').val();
  var lines = 10;
  var str = "";

  if(title==""){
    str += "Title should not be empty";
    lines+=18;
  }else if(title.length>50){
    if(str!="")
      str+= "<br/>";
    str = "Title should not be more than 50 characters";
    lines+=18;
  }
  if(desc!="" && desc.length>1000){
    if(str!="")
      str+= "<br/>";
    str += "Description should not be more than 1000 characters";
    lines+=18;
  }
  if(actDate==""){
    if(str!="")
      str+= "<br/>";
    str += "Activation date should not be empty";
    lines+=18;
  }
  if(status==0){
    if(str!="")
      str+= "<br/>";
    str += "Select any status";
    lines+=18;
  }
  if(status==0){
    if(str!="")
      str+= "<br/>";
    str += "Select any site to associate with this survey";
    lines+=18;
  }
  if (expDate != "") {
    var actObj = new Date(actDate.replace(/-/g,"/"))
    var expObj = new Date(expDate.replace(/-/g,"/"))
    if (actObj > expObj) {
      if(str!="")
        str+= "<br/>";
      str += "Expiration date should be greater than or equal to the Activation date";
      lines+=18;
    }
  }


  var actdate = actDate.split("-");
  if(actdate.length <3){
    if(str!="") str+= "<br/>";
    str += 'Please enter Valid date in Activation date field';
    lines+=18;
  }

  if(expDate!=''){
	  var expdate = expDate.split("-");
	  if(expdate.length <3){
		if(str!="") str+= "<br/>";
		str += 'Please enter Valid date in Expiration date field';
		lines+=18;
	  }
  }

  if(str!=""){
    resize_dialog(600, 305+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    return;
  }
    
  var mode = "edit";
  var url = "survey/edit_action/"+id;
  if($('#ui-dialog-title-dialog').html()=="Clone Survey"){
    url = "survey/clone/save/"+id;
    mode = "clone";
  }
  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+url,
    data: "title="+encodeURIComponent(title)+"&desc="+encodeURIComponent(desc.replace('\r\n','<br>'))+"&actDate="+actDate+"&expDate="+expDate+"&status="+status+(mode=="clone"?"&siteid="+siteid:"")+"&lang="+lang,
    async : true,
    cache : false,
    success : function (msg) {
      eval("var json="+msg);
      var url = 'survey/edit/'+id;
      var height = 0;
      if(mode=="clone"){
        url = 'survey/clone/'+id;
        height = 25;
      }
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        applyAction(1,$('#edit-apply').attr('actionitem'));
      }else{
        if(json.Error=="survey name already exist"){
          $.ajax({
            type : "GET",
            url : baseurl+url,
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              createDatePicker('edit-survey-actdate',0);
              createDatePicker('edit-survey-expdate',0);

              $('#edit-survey-description').val(desc);
              $('#edit-survey-title').val(title);
              $('#edit-survey-description').val(desc);
              $('#edit-survey-actdate').val(actDate);
              $('#edit-survey-expdate').val(expDate);
              $('#edit-survey-status').val(status);
              if(mode=="clone"){
                $('#edit-survey-site').val(siteid);
              }
              styleStatusMessages("Survey name already exists", "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
          resize_dialog(600, 305+30+height);
        }else{
          $.ajax({
            type : "GET",
            url : baseurl+url,
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              createDatePicker('edit-survey-actdate',0);
              createDatePicker('edit-survey-expdate',0);

              $('#edit-survey-description').val(desc);
              $('#edit-survey-title').val(title);
              $('#edit-survey-description').val(desc);
              $('#edit-survey-actdate').val(actDate);
              $('#edit-survey-expdate').val(expDate);
              $('#edit-survey-status').val(status);
              if(mode=="clone"){
                $('#edit-survey-site').val(siteid);
              }
              styleStatusMessages("Failure to save survey", "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
          resize_dialog(600, 305+30+height);
        }
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function setQuestionType(type){
  $('#edit-question-type').val(type);
  $('#edit-question-insert').val(type);
    
  //Hide the answer box if the selected type is a textbox or textarea
  if (type == "Textbox" || type == "Textarea") {
    $("#AnswerBox").hide();
  }
  else if (type != "Textbox") {
    $("#AnswerBox").show();
  }
}
var answers = new Array();
/*function addAnswers(){
  //Frame the array by getting the values from the text field
  var ans_str = $('#edit-question-answer').val();
  var type = $('#edit-question-type').val();
  var ans_val = '50';
  var ans_def = $('#edit-question-answer-default').val();
  //validations for entering answers
 

  if ($.trim(ans_str) == "") {
    styleStatusMessages("Please enter the answer", "statusMessage", "failure");
   
    return false;
  }
  if (isNaN(ans_val)) {
    styleStatusMessages("Please enter only numeric values", "statusMessage", "failure");
    return false;
  }
  $("#statusMessage").hide();
  var temp = null;
  //update the field based on their positions
  if ($("#editAnsID").val() != 0 && $("#editAnsID").val() != "") {
    temp = answers[$("#editAnsPos").val()];
    answers[$("#editAnsPos").val()] = [ans_val, ans_str, $("#editAnsID").val(), ans_def];
  }else if ($("#editAnsPos").val() != "") {
    temp = answers[$("#editAnsPos").val()];
    answers[$("#editAnsPos").val()] = [ans_val, ans_str, 0, ans_def];
  }
  else {
    answers.push([ans_val, ans_str, 0, ans_def]);
  }
  if (type != "Checkbox" && type != "Multiselect List" && type != "Multiselect Filtered List" && type != "Source-Target List") {
    var k=0;
    for(var i=0;i<answers.length;i++){
      if(answers[i][3]=='true'){
        k++;
      }
    }
    if(k > 1){
      styleStatusMessages("Please select only one default value", "statusMessage", "failure");
      if(temp!=null)
        answers[$("#editAnsPos").val()] = temp;
      $('#dialog').scrollTop(0);
      return false;
    }
  }
  
  //Display the array of values in UI
  drawAnswers();

  //Clear the fields after adding the values
  $('#edit-question-answer').val("");
  $('#edit-question-answer-value').val("");
  $('#edit-question-answer-default').val("false");
  $("#editAnsPos").val("");
  $("#editAnsID").val("");

  //rename the button
  $("#edit-answer-add-button").val("Add");

  //Focus the answer field after adding the value
  $('#edit-question-answer').focus();
  return false;
}*/
function addAnswers(){
  var type = $('#edit-question-type').val();
  //Frame the array by getting the values from the text field
  var ans = $('#edit-question-answer').val();
  var ans_val = $('#edit-question-answer-value').val();
  var ans_def = $('#edit-question-answer-default').val();
	
  //validations for entering answers
  //code to validate the fields
  var lines = 10;
  var str = "";
  if($.trim(ans) == "") {
    str += "Please enter the answer";
    lines+=18;
  }
	
  if (type != "Checkbox" && type != "Multiselect List" && type != "Multiselect Filtered List" && type != "Source-Target List") {
    if ($("#editAnsDef").val() != "true" || $("#editAnsDef").val() == "") {
      if(ans_def == 'true'){
        var k=0;
        for(var i=0; i<answers.length; i++){
          if(answers[i][3] == 'true'){
            k++;
          }
        }
        if(k>0){
          if(str!="")
            str+= "<br/>";
          str += "Please select only one default value";
          lines+=18;
        }
      }
    }
  }	

  if ($.trim(str)!= "") {
    resize_dialog(850,500+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
	
  $("#statusMessage").hide();
  //update the field based on their positions
  if ($("#editAnsID").val() != 0 && $("#editAnsID").val() != "") {
    answers[$("#editAnsPos").val()] = [ans_val, ans, $("#editAnsID").val(), ans_def];
  }
  else if ($("#editAnsPos").val() != "") {
    answers[$("#editAnsPos").val()] = [ans_val, ans, 0, ans_def];
  }
  else {
    answers.push([ans_val, ans, 0, ans_def]);
  }
  //Display the array of values in UI
  drawAnswers();
	
  //Clear the fields after adding the values
  $('#edit-question-answer').val("");
  $('#edit-question-answer-value').val("");
  $('#edit-question-answer-default').val("false");
  $("#editAnsPos").val("");
  $("#editAnsID").val("");
  $("#editAnsDef").val("");
	
  //rename the button
  $("#edit-answer-add-button").val("Add");
	
  //Focus the answer field after adding the value
  $('#edit-question-answer').focus();
}

function removeAnswers(pos, ansid){
  openConfirmBox(function(){
    if(ansid != 0){
      $.ajax({
        type : "POST",
        url : baseurl+"survey/actions/delete_answer/"+ansid,
        data: "status=&validateFrom=&validateTo=",
        async : true,
        cache : false,
        success : function (msg) {
          if(msg=="Success"){
            $('#alertdialog').dialog('destroy');
            answers.splice(pos, 1);
            drawAnswers();
          }
        },
        error : function (res) {
          handleRequestError(res);
        }
      });
    }
    else{
      $('#alertdialog').dialog('destroy');
      answers.splice(pos, 1);
      drawAnswers();
    }
  },300,100,"Confirm Delete","Do you want to delete this answer?");
}

function editAnswers(pos, ansid, ans, score, isDefault){
  //store the answerd edited in hidden field
  $("#editAnsPos").val(pos);
  $("#editAnsID").val(ansid);

  //Assign the edited values to the fields
  $("#edit-question-answer").val(ans);
  $("#edit-question-answer-value").val(score);
  $("#edit-question-answer-default").val(isDefault);
  //rename the button
  $("#edit-answer-add-button").val("Update");
}

function drawAnswers(){
  var str = '<div id="reorder"><ul>';
  for(var i=0;i<answers.length;i++){ 
    str += '<li><div class="'+(i%2==0?"row-dark":"row-light")+'"><input type="hidden" value="'+answers[i][2]+'" /><div class="left-title">'+answers[i][1]+'</div><div class="middle-title">'+((answers[i][3]=='true'||answers[i][3]==true)?'Default':'Non-default')+'</div><div class="right-anstext"><a href="javascript:void(0);" onclick="editAnswers('+i+', '+answers[i][2]+', \''+answers[i][1]+'\', 50, \''+((answers[i][3]=='true' || answers[i][3]=='1')?'true':'false')+'\')">Edit</a>&nbsp;&nbsp;&nbsp;<a href="javascript:void(0);" onclick="removeAnswers('+i+', '+answers[i][2]+')">Delete</a></div><div class="clearit" style="padding:0px;"></div></div></li>';
  }
  $('#answers').html(str+'</ul></div>');
  $("#reorder ul").sortable({
    opacity: 0.8,
    cursor: 'move',
    update: function() {
      store_answers();
    }
  });
}
function editSingleQuestion(sid, qid){
  reopen_dialog(850,500,"Edit Question");
  $.ajax({
    type : "GET",
    url : baseurl+'survey/question/'+sid+'/'+qid,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);

      $("#edit-question-answer").keyup(function(e) {
		  if(e.keyCode == 13) {
			 addAnswers();
		  }
      });  

      fckeditor('edit-question-description');
      $("#reorder ul").sortable({
        opacity: 0.8,
        cursor: 'move',
        update: function() {
          store_answers();
        }
      });
      $("#edit-question-insert").click(function(){
        var l = $('#edit-question-insert').position().left-1;
        var t = $('#edit-question-insert').position().top+22;
        if($.browser.msie && $.browser.version<8){
          l-=5;
        //l+=4
        //t+=33;
        }

        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function deleteSingleQuestion(sid, qid){
  openConfirmBox(function(){
    $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"survey/actions/delete_question/"+qid,
      data: "status=&validateFrom=&validateTo=",
      async : true,
      cache : false,
      success : function (msg) {
        if(msg=="Success"){
          $('#alertdialog').dialog('destroy');
          reopen_dialog(700,515,"Preview Question");
          preview_question_dialog(sid);
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  },300,100,"Confirm Delete","Do you want to delete this question?");
}

function activateSurvey(id, status, validateFrom, validateTo){
  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  if(status=="Active")
    status = "Inactive";
  else
    status = "Active";

  $.ajax({
    type : "POST",
    url : baseurl+"survey/actions/activate/"+id,
    data: "status="+status+"&validateFrom="+validateFrom+"&validateTo="+validateTo,
    async : true,
    cache : false,
    success : function (msg) {
      if(msg=="Success"){
        reopen_dialog(500,260,"View Survey");
        surveyDetails(id);
        $("#survey_statusCode"+id).html('<p>'+status+'</p>');
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function deleteSurvey(id, status, validateFrom, validateTo){
  var totrec = $('#hid_totalRec').val();
  var limit  = $('#hid_limit').val();
  var pageno = $("#hid_pageno").val();
  openConfirmBox(function(){
    $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"survey/actions/delete/"+id,
      data: "status="+status+"&validateFrom="+validateFrom+"&validateTo="+validateTo,
      async : true,
      cache : false,
      success : function (msg) {
        $('#alertdialog').dialog('destroy');
        if(msg=="Success"){
          $('#dialog').dialog('destroy');
          var remainderpageno = totrec % (limit * (pageno-1));
          if(remainderpageno == 1){
            pageno--;
          }
          applyAction(pageno,$('#edit-apply').attr('actionitem'));
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  },300,100,"Confirm Delete","Do you want to delete this survey?");
}

function viewReport(id, surveyname){
  reopen_dialog(700,410,surveyname+" - Report");
  $('#dialog').html('<div style="padding-top:180px; padding-left:330px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'survey/report/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editQuestionDialog(id){
  $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'survey/question/'+id,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);

      $("#edit-question-answer").keyup(function(e) {
		  if(e.keyCode == 13) {
			 addAnswers();
		  }
      });  

      fckeditor('edit-question-description');
      $("#reorder ul").sortable({
        opacity: 0.8,
        cursor: 'move',
        update: function() {
          store_answers();
        }
      });
      $("#edit-question-insert").click(function(){
        var l = $('#edit-question-insert').position().left-1;
        var t = $('#edit-question-insert').position().top+22;

        if($.browser.msie && $.browser.version<8){
          l-=5;
        //l+=4
        //t+=33;
        }
        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function preview_question_dialog(id){
  $('#dialog').html('<div style="padding-top:160px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'survey/preview/'+id+"/1/30",
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function backtoDetails(id){
  reopen_dialog(500,260,"View survey");
  $('#dialog').html('<div style="padding-top:90px; padding-left:230px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  surveyDetails(id)
}
function filterdata_survey(){
  //prepare the field values for filtering
  var search_survey = $.trim($("#edit-survey-search-details").val());
  var search_active = $("#edit-survey-search-active").val();
  var search_expire = $.trim($("#edit-survey-search-expire").val());
  var search_status = $.trim($("#edit-survey-search-status").val());

  var data = "";
  if($.trim(search_survey)!=""){
    data+="&search_survey="+search_survey;
  }
  if($.trim(search_active)!=""){
    data+="&search_active="+search_active;
  }
  if($.trim(search_status)!="" && search_status != "ANY"){
    data+="&search_status="+search_status;
  }
  if($.trim(search_expire)!=""){
    data+="&search_expire="+search_expire;
  }
  return data;
}



var ckeditor;
function fckeditor(id){
  if(!ckeditor){
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }else{
    if (CKEDITOR.instances[id]) {
      CKEDITOR.remove(CKEDITOR.instances[id]);
    }
    ckeditor=null;
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }
  $('.ui-dialog').css("filter","");
}

function cloneSurvey(id){
  reopen_dialog(600, 335, "Clone Survey");
  $('#dialog').html('<div style="padding-top:100px; padding-left:270px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'survey/clone/'+id,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('edit-survey-actdate',0);
      createDatePicker('edit-survey-expdate',0);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function export_report(surveyid, name){
  $('#common-actions').attr('action',baseurl+"survey/export?id="+surveyid+"&name="+name);
  $('#common-actions').submit();
}

function export_all_report(){
  $('#common-actions').attr('action',baseurl+"survey/export?all=all");
  $('#common-actions').submit();
}

function reorderpopup(id){
  $('#dialog').html('<div style="padding-top:160px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'survey/reorder/'+id,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      $("#reorder ul").sortable({
        opacity: 0.8,
        cursor: 'move',
        update: function() {
          $("#saveorder").show();
        }
      });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to save the reordered list
function save_reorder (id) {
  var neworder = Array();
  $("#reorder .gridlister").each(function() {
    neworder.push($(this).attr("id").split("_")[1]);
  });
  
  $('#dialog').html('<div style="padding-top:240px; padding-left:305px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    data : "newOrder="+neworder,
    url : baseurl+'survey/reorder/'+id+'/save',
    async : true,
    cache : false,
    success : function (msg) {
      eval("var json="+msg);
      if(json.Message=="Success"){
        previewQuestion(id);
        
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function store_answers(){
// Dummy method. have to remove
}

function get_answers(){
  var i=0;
  answers = new Array();
  $("#reorder li").each(function() {
    var obj = $(this).get(0).getElementsByTagName("input")[0];
    var id = obj.value;
    var ans = $(obj).next().html();
    var def = $(obj).next().next().html();
    if(def=="Default"){
      def = true;
    }else{
      def = false;
    }
    answers[i] = ["50", ans, id, def];
    i++;
  });
}
/**
 *  Function to open dialog box          Shashi 14 Oct 09
 */
function viewDateWiseReportForm(id, width, height, title){
  openDialog("datewisesurvey",0,width,height,title);
}

/**
 *  Function to show form for selecting date range to view report          Shashi 14 Oct 09
 */
function viewDateWiseReport(){
  $.ajax({
    type : "GET",
    url : baseurl+'survey/datewisereport',
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('edit-date-range-from',-365);
      createDatePicker('edit-date-range-to',-364);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
/**
 *  Function to show report for selected range          Shashi 14 Oct 09
 */
function showDateWiseReport(){
  var fromDate = $('#edit-date-range-from').val();
  var toDate   = $('#edit-date-range-to').val();

  var from_Date = new Date(fromDate.replace(/-/g,"/"));
  var to_Date = new Date(toDate.replace(/-/g,"/"));
	
  var lines = 10;
  var str = "";
  if($.trim(fromDate) == "") {
    str += "Please select Date From";
    lines+=18;
  }
  if($.trim(toDate) == "") {
    if(str!="")
      str+= "<br/>";
    str += "Please select Date To";
    lines+=18;
  }
  if ($.trim(fromDate) != "" && $.trim(toDate) != "") {
    if (to_Date < from_Date) {
      if(str!="")
        str+= "<br/>";
      str += "Date To should be greater than Date From";
      lines+=18;
    }
  }

  if (str != "") {
    resize_dialog(400, 150+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return false;
  }
	
  reopen_dialog(700, 400, "Survey - Date Wise Report");
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'survey/showdatewisereport?&fromDate='+encodeURIComponent(fromDate)+'&toDate='+encodeURIComponent(toDate),
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

function export_all_report_datewise(dateFrom, dateTo){
  $('#common-actions').attr('action',baseurl+"survey/exportdatewisereport?dateFrom=" + dateFrom + "&dateTo=" + dateTo);
  $('#common-actions').submit();
}

//Function to go back the date wise report form 
function goBackToDateWiseReportForm () {
  reopen_dialog(400, 150, 'Survey - Date Wise Report');
  viewDateWiseReport();
}